package hamburgerwang.businfo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;

public class SettingsDialog extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Preference pref = findPreference(key);
		this.setSummary(pref);
	}

	private final static String RPOXY_SET = "proxy_set";
	private final static String RPOXY_HOST = "proxy_host";
	private final static String RPOXY_PORT = "proxy_port";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.settings);
		initSummaries(this.getPreferenceScreen());
		getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(this);
	}

	public static boolean getProxySet(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getBoolean(RPOXY_SET, false);
	}

	public static String getProxyHost(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(RPOXY_HOST, "127.0.0.1");
	}

	public static int getProxyPort(Context context) {
		return Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(
				context).getString(RPOXY_PORT, "80"));
	}

	/**
	 * Set the summaries of all preferences
	 */
	private void initSummaries(PreferenceGroup pg) {
		for (int i = 0; i < pg.getPreferenceCount(); ++i) {
			Preference p = pg.getPreference(i);
			if (p instanceof PreferenceGroup)
				this.initSummaries((PreferenceGroup) p); // recursion
			else
				this.setSummary(p);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Unregister the listener whenever a key changes
		getPreferenceScreen().getSharedPreferences()
				.unregisterOnSharedPreferenceChangeListener(this);

	}

	/**
	 * Set the summaries of the given preference
	 */
	private void setSummary(Preference pref) {
		// react on type or key
		if (pref instanceof ListPreference) {
			ListPreference listPref = (ListPreference) pref;
			pref.setSummary(listPref.getEntry());
		} else if (pref instanceof EditTextPreference) {
			pref.setSummary(((EditTextPreference) pref).getText());
		} else if (pref instanceof CheckBoxPreference) {
			pref
					.setSummary(((CheckBoxPreference) pref).isChecked() ? R.string.proxy_set_true
							: R.string.proxy_set_false);
		} else {

		}
	}
}
